<template>
  <div class="content">
    <jc-button
      :btn-arr="['reload', 'sub', 'remove', 'option', 'pass', 'push', 'batchFill']"
      :disab-arr="['close', 'cancel', 'using', 'com1', 'com2', 'freeze']"
      :fbillno="fbillno"
      url="tPrdOutsource/queryOutsourceList"
      @refresh="handleGetUntreated"
      @audit="audit(1)"
      @noAudit="audit(2)"
      @submit="submit(1)"
      @noSubmit="submit(2)"
      @del="delPublic"
      @toExcel="handleExport"
      @pushDown="pushDown"
    />
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="handleQuerySonClass"
        />
        <el-button type="primary" class="btn" size="mini" @click="handleQuerySonClass">{{ $t('btn.search') }}</el-button>
        <filtration
          :ftype="ftype"
          :msg="tacitly"
          :select-data="selectData"
          :table-header="tableHeader1"
          :detail-header="tableHeader"
          @seachData="handleQuerySonClass"
        />
      </div>
    </div>
    <div class="table-content">
      <jc-table
        v-loading="loading"
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        table-selection
        sortable
        get-row-keys="fentryid"
        :get-summaries="getSummaries"
        show-summary
        @selectionChange="handleSelectAll"
        @clickRow="detailPurchase"
      >
        <!--订单编码-->
        <template v-slot:tagSlot="col">
          <el-link type="primary" @click="detailPurchase(col.scope.row)">{{ col.scope.row.fbillNo }}</el-link>
        </template>
        <!--    物料编码    -->
        <template v-slot:orderSlot="col">
          <el-link type="primary" @click="jumpMateriel(col.scope.row)">
            {{ col.scope.row.fnumber }}
          </el-link>
        </template>
        <!--审核状态-->
        <template v-slot:btnState="col">
          <span v-if="col.scope.row.fdocumentstatus === ''" />
          <el-tag v-else :type="col.scope.row.stateColor">{{ col.scope.row.fdocumentstatus }}</el-tag>
        </template>
      </jc-table>
    </div>
    <!--    分页器-->
    <div class="footer">
      <jc-pagination
        :total="total"
        :page.sync="currentPage"
        :limit.sync="size"
        @pagination="handleGetUntreated"
      />
    </div>
    <el-dialog
      v-dialogDrag
      :title="$t('market.checkBill')"
      model
      :visible.sync="isdanjuDialog"
      :close-on-click-modal="false"
      width="600px"
      center
    >
      <div style="text-align: center;height: 100px;line-height: 100px">
        <el-radio-group v-model="orderLX" @change="handleOrder">
          <el-radio v-for="item in receipts" :key="item" :label="item">{{ item }}</el-radio>
        </el-radio-group>
      </div>
      <hr>
      <div style="text-align: center;">
        {{ $t('market.rule') }}
        <el-input v-model="convert" size="mini" disabled style="width: 178px;margin-bottom: 5px;" />
        <br>
        {{ $t('market.billType') }}
        <el-select
          v-model.trim="fbillTypeId"
          size="mini"
          filterable
        >
          <el-option
            v-for="(item, index) in billTypeData"
            :key="index"
            :label="item.fname"
            :value="item.fid"
          />
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isdanjuDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="pushDownOrder()">{{ $t('btn.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryOutsourceList,
  outsourceAudit,
  outsourceUnAudit,
  outsourceSubmit,
  outsourceAuSubmit,
  outsourceDelete, pushToFinPayableFromMulOutSource, pushOutsourceInStock
} from '@/api/production/process'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { toMxBmina } from '@/components/ToMxamineState'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import filtration from '@/components/filtration'
import jcButton from '@/components/Button'
import { queryViewItem } from '@/api/marketManage/marketOrder'

export default {
  name: 'OutProcess',
  components: {
    search,
    filtration,
    jcButton
  },
  mixins: [searData],
  data() {
    return {
      orderLX: this.$t('menu.outStorageOrder'),
      receipts: [this.$t('menu.payable'), this.$t('menu.outStorageOrder')], // 生产'应付单''外包入库单'
      fbillTypeId: 1427,
      convert: this.$t('market.wbzyf'),
      billTypeData: [], // 采购订单单据
      isdanjuDialog: false,
      ftype: 52,
      total: 0, // 总条目
      currentPage: 1, // 当前页
      size: 200, // 每页显示多少条数据
      // 表头
      tableData: [], // 销售数据
      tableHeight: '70vh',
      fbillno: '',
      tableHeader: [
        { label: this.$t('market.fdate'), prop: 'fdate', width: '90' },
        { label: this.$t('market.billNo'), type: 'tag', prop: 'fbillNo', width: '120' },
        { label: this.$t('market.documentstatus'), type: 'state', prop: 'fdocumentstatus', width: '100' },
        { label: this.$t('market.srcbillno'), prop: 'fsrcbillno', width: '120' },
        { label: this.$t('market.srcmoqty'), prop: 'fmoqty', align: 'right', width: '80' },
        { label: this.$t('market.supplier'), prop: 'fsupplier' },
        { label: this.$t('market.fmodel2'), prop: 'fmodel' },
        { label: this.$t('market.fmaterial'), prop: 'fnumber', type: 'order', width: '130' },
        { label: this.$t('shop.fname2'), prop: 'fname' },
        { label: this.$t('market.multiple'), prop: 'fnum', width: '80', align: 'right' },
        { label: this.$t('market.nowfprice'), prop: 'fnowfprice', width: '80', align: 'right' },
        { label: this.$t('market.nowsumprice'), prop: 'fnowsumprice', width: '80', align: 'right' }
      ],
      tableHeader1: [],
      proData: []
    }
  },
  created() {
    this.handleGetUntreated()
    this.tableHeader1 = this.tableHeader
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 230px)' : '73vh'
  },
  methods: {
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else if (this.val && this.val.length > 0) {
          const list = this.val.map(item => {
            return toMxBmina(item)
          })
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '外包工序单列表')
        } else {
          queryOutsourceList({
            pageSize: 5000,
            pageNum: 1,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.array.map(item => {
                return toMxBmina(item)
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '外包工序单列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 获取外包工序单列表
    async handleGetUntreated(ev) {
      this.loading = true
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      const DATA = {
        pageNum: this.currentPage,
        pageSize: this.size,
        search: this.searCollData.concat(this.details)
      }
      const RES = await queryOutsourceList(DATA)
      if (RES.code === 0) {
        this.loading = false
        this.tableData = RES.data.array.map(item => {
          return toMxBmina(item)
        })
        this.total = RES.data.total
      } else {
        this.loading = false
        this.$confirm(RES.message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 搜索
    handleQuerySonClass(ev) {
      this.currentPage = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.handleGetUntreated(ev.detail)
      } else {
        this.handleGetUntreated()
      }
    },
    // 详情
    detailPurchase(ev) {
      const id = ev.fid
      this.$router.push({ path: `/outProcessDetail/${id}` })
    },
    handleSelectAll(val) {
      this.val = val
      this.fbillno = val[0].fbillNo
      this.selectVal = []
      this.pushVal = []
      this.EntryIds = []
      val.forEach(res => {
        res.fbillNo && this.selectVal.push(res.fbillNo)
        res.fid && this.pushVal.push(res.fid)
        res.fentryid && this.EntryIds.push(res.fentryid)
      })
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: this.selectVal }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.selectVal = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
        this.handleGetUntreated()
      })
    },
    // 审批通过
    async audit(ev) {
      if (this.selectVal.length === 0) {
        this.$message({ showClose: true, message: '请选择数据', type: 'warning' })
        return
      }
      const api = ev === 1 ? outsourceAudit : outsourceUnAudit
      this.toExamineFun(api)
    },
    // 提交、反提交
    async submit(ev) {
      const api = ev === 1 ? outsourceSubmit : outsourceAuSubmit
      this.toExamineFun(api)
    },
    // 删除
    delPublic() {
      this.$confirm('此操作将永久删除该订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const api = outsourceDelete
        this.toExamineFun(api)
      })
    },
    // 下推
    pushDown() {
      if (this.pushVal && this.pushVal.length <= 0) {
        this.$message.error('请选择数据!')
        return
      }
      this.queryTBasBilltype('SX_OUTSOURCE_INSTOCK')
      this.isdanjuDialog = true
    },
    handleOrder(val) {
      if (val === this.$t('menu.payable')) {
        this.convert = this.$t('market.wbzyf') // '外包单至标准应付单'
        this.fbillTypeId = 1249
        this.queryTBasBilltype('SX_PAYABLEBILLTYPE')
      } else if (val === this.$t('menu.outStorageOrder')) {
        this.convert = this.$t('market.wbzrk') // '外包单至外包入库单'
        this.fbillTypeId = 1427
        this.queryTBasBilltype('SX_OUTSOURCE_INSTOCK')
      }
    },
    // 查询单据类型
    async queryTBasBilltype(ev) {
      const { data: RES } = await queryViewItem({ viewName: ev })
      this.billTypeData = RES.list
    }, // 外包单下推标准应付单
    pushDownOrder() {
      const DATA = {
        SourceIds: this.pushVal,
        EntryIds: this.EntryIds,
        fbillTypeId: this.fbillTypeId
      }
      if (this.orderLX === this.$t('menu.payable')) {
        pushToFinPayableFromMulOutSource(DATA).then(res => {
          if (res.code === 0) {
            this.isdanjuDialog = false
            this.$router.push({ path: `/payableDetail/${res.data.fid}` })
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.outStorageOrder')) {
        pushOutsourceInStock(DATA).then(res => {
          if (res.code === 0) {
            this.isdanjuDialog = false
            this.$router.push({ path: `/outStorageDetail/${res.data.fid}` })
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      }
    },
    // 自定义列表
    customHandle(ev) {
      this.tableHeaders = []
      if (ev.header) {
        ev.header.forEach(item => {
          this.tableHeader1.forEach(res => {
            if (res.label === item) {
              this.tableHeaders.push(res)
            }
          })
        })
        this.tableHeader = this.tableHeaders
      } else if (ev.fname === '缺省方案') {
        this.tableHeader = this.oldTabHeader
      } else {
        this.tableHeader = this.tableHeader1
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.content {
  @include listBom;

  .header{
    position:relative;
    .header-name{
      width: 100%;
    }
    .btn{
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
}
</style>
